﻿using System;
using System.Reflection;
using System.Web.Mvc;
using xmgl.Bll;
using xmgl.Common;
using xmgl.Models;

namespace xmgl.Controllers
{
    [Authorization]//如果将此特性加在Controller上，那么访问这个Controller里面的方法都需要验证用户登录状态
    public class HomeController : Controller 
    {
        protected log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        static Constant c = new Constant();//常量初始化。

        // GET: Home
        public ActionResult Index()
        {
            ViewBag.name = Session[Constant.LoginedUser].ToString();
            return View();
        }
        [HttpGet, AllowAnonymous]//这里是一个特例，有这个特性，表示这个方法不需要验证用户登录状态
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost, AllowAnonymous]
        public JsonResult Login(string name, string pwd)
        {
            var res = new JsonResult();
            try
            {
                //DbBaseContext db = new DbBaseContext();

                Log.Debug("尝试登录name:" + name + ",pwd:" + pwd);
                UserBll bll = new UserBll();
                if (bll.Login(new User { LoginName = name, Password = pwd }))
                {
                    Session[Constant.LoginedUser] = "admin";
                    res.Data = new { error = false, msg = "登录成功" };
                }
                else
                {
                    res.Data = new { error = true, msg = "登录失败" };
                }
            }
            catch (Exception ex)
            {
                res.Data = new { error = true, msg = "登录失败" };
                Log.Error(ex);
            }
            return res;
        }

        public ActionResult ModifyPwd()
        {
            return View();
        }
        [HttpPost]
        public JsonResult ModifyPwd(string name, string oldPwd, string newPwd)
        {
            var res = new JsonResult();
            res.ContentType = "text/html";
            UserBll bll = new UserBll();
            if (bll.ModifyPwd(new User { LoginName = name, Password = oldPwd }, newPwd))
            {
                res.Data = new { error = false, msg = "修改密码成功。" };
                return res;
            }
            else
            {
                res.Data = new { error = true, msg = "修改密码失败。" };
                return res;
            }
        }
    }
}